#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/loadavg.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>

#define err() do { perror("server9"); exit(EXIT_FAILURE); } while(0)

pid_t pid;
uid_t uid;
gid_t gid;
double load[3];
time_t cur;

void sighan(int sig)
{
	switch(sig)
	{
		case SIGHUP:
			printf("pid:%ld\n", pid);
			if(signal(SIGHUP, sighan) == SIG_ERR) err();
			break;
		case SIGINT:
			printf("uid:%ld\n", uid);
			if(signal(SIGINT, sighan) == SIG_ERR) err();
			break;
		case SIGTERM:
			printf("gid:%ld\n", gid);
			if(signal(SIGTERM, sighan) == SIG_ERR) err();
			break;
		case SIGUSR1:
			printf("seconds:%ld\n", cur);
			if(signal(SIGUSR1, sighan) == SIG_ERR) err();
			break;
		case SIGUSR2:
			printf("1:%f\t5:%f\t15:%f\n", load[0], load[1], load[2]);
			if(signal(SIGUSR2, sighan) == SIG_ERR) err();
			break;
	}	
	fflush(stdout);
}

int main(int argc, char *argv[])
{
	time_t start;
	pid = getpid();
	uid = getuid();
	gid = getgid();
	start = time(NULL);
	if(signal(SIGHUP, sighan) == SIG_ERR) err();
	if(signal(SIGINT, sighan) == SIG_ERR) err();
	if(signal(SIGTERM, sighan) == SIG_ERR) err();
	if(signal(SIGUSR1, sighan) == SIG_ERR) err();
	if(signal(SIGUSR2, sighan) == SIG_ERR) err();
	putchar(0);
	for(;;)
	{
		cur = time(NULL) - start;
		if(getloadavg(load,3) == -1) err();
		sleep(1);
	}
	return 0;
}
